package util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author yangjingyi
 * 
 */
public class URLHandler {
	// 根据URL获取网页内容
	public static String getURLContext(String targetUrl) throws IOException {
		StringBuffer res = new StringBuffer();
		URL url;
		url = new URL(targetUrl);
		System.out.println("targetUrl " + targetUrl);

		URLConnection conn = url.openConnection();
		conn.setRequestProperty("accept", "*/*");
		conn.setRequestProperty("connection", "Keep-Alive");
		conn.setRequestProperty("user-agent",
				"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
		// conn.setRequestProperty("Referer", Constants.INDEX);
		conn.setConnectTimeout(3000);
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.connect();

		BufferedReader br = new BufferedReader(new InputStreamReader(
				conn.getInputStream(), "gb2312"));
		if (br != null) {
			String s = null;
			int c = 0;
			int i = 0;
			while ((s = br.readLine()) != null) {
				res.append(s);
			}
			br.close();
		}
		String result = res.toString();
		return result;
	}

	// 根据URL获取网页内容，设定编码格式
	public static String getURLContext(String targetUrl, String coding)
			throws IOException {
		StringBuffer res = new StringBuffer();
		URL url;
		url = new URL(targetUrl);

		BufferedReader br = new BufferedReader(new InputStreamReader(
				url.openStream(), coding));
		if (br != null) {
			String s = null;
			while ((s = br.readLine()) != null) {
				res.append(s);
			}
			br.close();
		}

		String result = res.toString();

		return result;
	}

	// 检测URL是否存在
	public boolean isConnect(String url) {
		boolean flag = false;
		int counts = 0;
		if (url == null || url.length() <= 0) {
			return flag;
		}
		while (counts < 5) {
			try {
				HttpURLConnection connection = (HttpURLConnection) new URL(url)
						.openConnection();
				int state = connection.getResponseCode();
				if (state == 200) {
					flag = true;
				}
				break;
			} catch (Exception ex) {
				counts++;
				continue;
			}
		}
		return flag;
	}

}
